<template>
  <div class="add-enterprise">
    <!--  头部  -->
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"> <i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id ?"编辑企业":"添加企业" }}</span>
      </div>
      <div class="right">
        管理员
      </div>
    </header>
    <!--  主要内容  -->
    <main class="add-main">
      <div class="form-container">
        <div class="title">
          企业信息
        </div>
        <div class="form">
          <el-form ref="ruleForm" :model="addForm" :rules="addFormRule" label-width="100px">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <!--              <el-input v-model="addForm.industryCode" />-->
              <el-select v-model="addForm.industryCode" placeholder="请选择" size="medium">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseId">
              <el-upload
                action="#"
                :http-request="uploadRequest"
                :before-upload="beforeUpload"
              >
                <el-button type="primary">上传文件</el-button>
                <div slot="tip" class="el-upload__tip">
                  支持扩展名：.png .jpg .jpeg，文件大小不得超过5M</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetForm">重置</el-button>
        <el-button type="primary" @click="confirmSubmit">确定</el-button>
      </div>
    </footer>

  </div>
</template>

<script>
import {
  getIndustryListAPI,
  addEnterpriseAPI,
  getEnterpriseByIdAPI,
  updateEnterpriseAPI
} from '@/api/enterprise'
import { upLoadFileAPI } from '@/api/comment'
const validatePhone = (rule, value, callback) => {
  if (/^1[3-9]\d{9}$/.test(value)) {
    callback()
  } else {
    callback(new Error('请输入正常的手机号'))
  }
}
export default {
  name: 'EnterpriseAdd',
  data() {
    return {
      industryList: [], // 行业列表
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      // 规则校验
      addFormRule: {
        name: [{
          required: true, message: '企业为必填项', trigger: 'blur'
        }],
        legalPerson: [{
          required: true, message: '法人为必填项', trigger: 'blur'
        }],
        registeredAddress: [{
          required: true, message: '注册地址为必填项', trigger: 'blur'
        }],
        industryCode: [{
          required: true, message: '所在行业为必填项', trigger: 'blur'
        }],
        contact: [{
          required: true, message: '企业联系人为必填', trigger: 'blur'
        }],
        contactNumber: [{
          required: true, message: '企业联系人电话为必填', trigger: 'blur'
        }, {
          validator: validatePhone, trigger: 'blur'
        }],
        businessLicenseId: [{
          required: true, message: '请上传营业执照', trigger: 'blur'
        }]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  mounted() {
    this.getIndustryList()
    if (this.id) {
      this.getEnterprise()
    }
  },
  methods: {
    // 查询企业
    async getEnterprise() {
      const res = await getEnterpriseByIdAPI(this.id)
      const { name, id, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseId, contact, contactNumber } = res.data
      this.addForm = { name, id, legalPerson, registeredAddress, industryCode, businessLicenseUrl, businessLicenseId, contact, contactNumber }
    },
    // 创建
    confirmSubmit() {
      this.$refs.ruleForm.validate(async valid => {
        console.log(valid)
        if (!valid) { return }
        let res
        if (!this.id) {
          res = await addEnterpriseAPI(this.addForm)
        } else {
          res = await updateEnterpriseAPI(this.addForm)
        }
        if (res.code === 10000) {
          this.$message.success(this.id ? '更新成功' : '添加成功')
          this.$router.back()
        } else {
          this.$message.error(this.id ? '更新失败, error' + res.msg : '添加失败, error' + res.msg)
        }
      })
    },
    async getIndustryList() {
      const res = await getIndustryListAPI()
      this.industryList = res.data
    },
    // 文件上传
    async uploadRequest(oFile) {
      const file = oFile.file
      // 处理formData 类型参数
      const formData = new FormData()
      formData.append('file', file)
      formData.append('type', 'businessLicense')
      const res = await upLoadFileAPI(formData)
      // 复制给表单
      this.addForm.businessLicenseId = res.data.id
      this.addForm.businessLicenseUrl = res.data.url

      // 校验上传逻辑
      this.$refs.ruleForm.validateField('businessLicenseId')
    },
    beforeUpload(file) {
      // 支持扩展名：.png .jpg .jpeg，文件大小不得超过5M
      // const isPng = file.type === 'image/png'
      // const isJPG = file.type === 'image/jpg'
      // const isJpeg = file.type === 'image/jpeg'
      const allowImgType = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5
      // if (!isPng && !isJPG && !isJpeg) {
      //   this.$message.error('上传只支持扩展名：.png .jpg .jpeg!')
      // }
      if (!allowImgType) {
        this.$message.error('上传只支持扩展名：.png .jpg .jpeg!')
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!')
      }
      return allowImgType && isLt5M
    },
    // 重置数据
    resetForm() {
      // resetFields
      this.$refs.ruleForm.resetFields()
    }

  }
}
</script>

<style scoped>
.add-enterprise{
  background-color: #f4f6f8;
  height: 100vh;
  .add-header{
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;
    .left {
      span {
        margin-right: 4px;
      }
      .arrow{
        cursor: pointer;
      }
    }
    .right {
      text-align: right;
    }
  }
  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left:20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form{
          display: flex;
          flex-wrap: wrap;
          .el-form-item{
            width: 50%;
          }
        }
      }
    }
  }
  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
